<?php

namespace App\Http\Controllers\Admin;


use App\Models\Inventory;
use App\Models\Role;
use App\Models\Supplier;
use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel as Excel;
use App\Imports\excelImport;
use App\Imports\PurchaseImport;
use App\Models\ProductsApproval;
use App\Models\OperationRecord;
use SoapClient;
use SoapFault;
use function Symfony\Component\VarDumper\Dumper\esc;

class SurgicalController extends Controller
{
    /**
     * 出库管理
     */
    public function maintainIndex(Request $request){
        return view('admin.surgical.xs_details_index');
    }
    public function detailsData(Request $request){
        $search = [];
        $search['product_code'] = $request->product_code?:'';
        $search['customer_name'] = $request->customer_name?:'';
        $search['date'] = $request->date?:'';
        $where = [];
        $now_page=intval($request->input('page'));
        $per_page_num=intval($request->input('limit'));
        //偏移量
        $offset=($now_page-1)*$per_page_num;
        if($offset<0) $offset=0;

        $inventoryModel = new Inventory();
        $where = [];

        $res = $inventoryModel->getXsDetailsDataList($where,$search,$offset,$per_page_num);
        $data = ['code' => 0,'msg' => '正在请求中...','count' => $res['count'],'data' => $res['data']];
        return response()->json($data);

    }



    public function generateIndex(Request $request)
    {

        $fieldArr = $this->getFieldData();

        return view('admin.surgical.xs_index',['fieldArr'=>$fieldArr]);
    }

    public function generateData(Request $request)
    {
        $search = [];
        $search['yao_customer_name'] = $request->yao_customer_name?:'';
        $search['ytx_code'] = $request->ytx_code?:'';
        $search['date'] = $request->date?:'';
        $now_page=intval($request->input('page'));

        $per_page_num=intval($request->input('limit'));
        //偏移量
        $offset=($now_page-1)*$per_page_num;
        if($offset<0) $offset=0;

        $inventoryModel = new Inventory();
        $where = [];
        $res =  $inventoryModel->getXsTotalList($where,$search,$offset,$per_page_num);

        $data = ['code' => 0,'msg' => '正在请求中...','count' => $res['count'],'data' => $res['data']];
        return response()->json($data);
    }



    public function generateTotal()
    {
        // 根据当前日期生成上个月的年月
        $currentDate = date('Y-m-d');
        $firstDayOfPreviousMonth = date('Y-m-01', strtotime('-1 month', strtotime($currentDate)));
        $lastDayOfPreviousMonth = date('Y-m-t', strtotime($firstDayOfPreviousMonth));
        $previousMonth = date('Y-m', strtotime('-1 month', strtotime($currentDate)));
        // 按条件删除 v_rk_total 表中的数据
        DB::table('v_xs_total')->where('data_time', $previousMonth)->delete();

        $inventoryModel = new Inventory();
        $where = [
            'start_time' => $firstDayOfPreviousMonth,
            'end_time' => $lastDayOfPreviousMonth,
        ];

        // 获取库存销售数据
        $results = $inventoryModel->getInventoryXsData($where);
        if (!$results || !isset($results['data'])) {
            return ['code' => 1, 'msg' => '无数据'];
        }

        // 初始化统计数组
        $amountStats = [];
        $randomNumber = 'CK'.mt_rand(10000000, 99999999);
        foreach ($results['data'] as $row) {

            if (!isset($amountStats[$row['customer_code']])) {
                $amountStats[$row['customer_code']] = [
                    'customer_code' => $row['customer_code'],
                    'customer_name' => $row['customer_name'],
                    'tax_excluded_amount' => 0, // 初始化为客户自己的合计
                    'tax_amount' => 0,
                    'amount_out' => 0,
                    "total_1" => 0, //原材料--卫生材料--一次性高值
                    "total_2" => 0,//原材料--卫生材料--其他
                    "total_3" => 0,//原材料--其他材料--其他材料
                    "total_4" => 0,//库存商品_西药
                    "total_5" => 0,//库存商品--设备
                ];
            }
            //累计数据
            $amountStats[$row['customer_code']]['tax_excluded_amount'] += $row['tax_excluded_amount'];
            $amountStats[$row['customer_code']]['tax_amount'] += $row['tax_amount'];
            $amountStats[$row['customer_code']]['amount_out'] += $row['amount_out'];
            if ($row['type_id'] == '01') {
                $amountStats[$row['customer_code']]['total_1'] += $row['cost_tax_excluded'];
            }
            if (in_array($row['type_id'], ['02', '07'])) {//08
                $amountStats[$row['customer_code']]['total_2'] += $row['cost_tax_excluded'];
            }
            if (in_array($row['type_id'], ['03', '04', '05'])) {
                $amountStats[$row['customer_code']]['total_3'] += $row['cost_tax_excluded'];
            }
            if (in_array($row['type_id'], ['06', '09'])) {
                $amountStats[$row['customer_code']]['total_4'] += $row['cost_tax_excluded'];
            }
            if ($row['type_id'] == '08') {
                $amountStats[$row['customer_code']]['total_5'] += $row['cost_tax_excluded'];
            }

        }
        foreach ($amountStats as $customerId => $row){
            $supplierFieldData = $inventoryModel->getCustomerFieldData(['yao_supplier_code' => (int)$row['customer_code']]);
            $finalResults[] = [
                'code'=>$randomNumber,
                'yao_customer_code' => $row['customer_code'],
                'yao_customer_name' => $row['customer_name'],
                'income' => $row['tax_excluded_amount'], // 收入
                'sales_tax' => $row['tax_amount'], // 销项税
                'tax_inclusive_amount' => $row['amount_out'], // 含税金额
                'total_1' => $row['total_1'], // 成本
                'total_2' => $row['total_2'], // 成本
                'total_3' =>$row['total_3'], // 成本
                'total_4' => $row['total_4'], // 成本
                'total_5' => $row['total_5'], // 成本
                'jin_customer_code' => $supplierFieldData['jin_customer_code']??0,
                'jin_customer_name' => $supplierFieldData['jin_customer_name']??0,
                'customer_calculation' => $supplierFieldData['type']??0,
                'data_time'=>$previousMonth

            ];
        }

        // 批量插入数据
        if (!empty($finalResults)) {
            $res = DB::table('v_xs_total')->insert($finalResults);
        }
        if ($res){
            return response()->json(['code'=>0,'msg'=>'生成成功']);
        }else{
            return response()->json(['code'=>401,'msg'=>'生成失败']);
        }

        // 返回最终统计数据
        return ['code' => 0, 'data' => $finalResults];
    }




  public function generateCertificate(Request $request)
  {
      $id = $request->get('id');
      if (!$id){
          return response()->json(['code'=>204,'msg'=>'参数错误']);
      }
      $inventoryModel = new Inventory();
      $info = $inventoryModel->getOneData('v_xs_total',['id'=>$id]);
      if (!$info){
          return response()->json(['code'=>204,'msg'=>'数据错误']);
      }
      $custResult['data'] = 0;
      $costResult['data'] = 0;
      //内部 无税金额 税额 含税金额计算
      if($info['customer_calculation'] == 1){
          // 内部收入
          $info['account_number_1'] = '6001.01.01';
          $info['abstract_excluded'] = '主营业务收入_内部销售_药装产品销售';
          $custResult = $this->setStoredOutData($info);
          // 内部成本
          $info['account_cost_number'] = '6401.01.01';
          $info['abstract_cost_excluded'] = '医疗业务成本_内部销售成本_药装产品成本';
          $costResult = $this->setCostOutData($info);
      }
      if($info['customer_calculation'] == 2){
          // 外部收入
          $info['account_number_1'] = '6001.02.01';
          $info['abstract_excluded'] = '主营业务收入_外部销售_药装产品销售';
          $custResult = $this->setStoredOutData($info);
          // 外部成本
          $info['account_cost_number'] = '6401.02.01';
          $info['abstract_cost_excluded'] = '医疗业务成本_外部销售成本_药装产品成本';
          $costResult = $this->setCostOutData($info);
      }
       if ($custResult['code'] != 0 && $costResult['code'] != 0){
           return response()->json(['code'=>500,'msg'=>'生成凭证失败']);
       }
      return response()->json(['code'=>0,'msg'=>'生成凭证成功！']);

  }
    public function setCostOutData($info)
    {
        //计算收入
        $info['cost_total'] = array_sum([$info['total_1'],$info['total_2'],$info['total_3'],$info['total_4'],$info['total_5']]);
        $inventoryModel = new Inventory();
        if($info['cost_total']){
            $info['cost_total'] = $info['cost_total']; //  收入
            $info['account_number_1'] = $info['account_cost_number'];
            $info['abstract_excluded'] = $info['abstract_cost_excluded'];
            $info['asstActType1'] = '客户';
        }

        $certificateData = $inventoryModel->setCostOutData($info);
        $url = 'http://8.152.0.162/eas/loginAndVoucher';
        $result = $this->KingdeePost($url, $certificateData);
        if ($result === false) {
            return response()->json(['code' => 500, 'msg' => '调用金蝶接口失败']);
        }

        $decodedResult = json_decode($result, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($decodedResult)) {
            // JSON 解析失败或不是数组
            return response()->json(['code' => 500, 'msg' => '金蝶接口返回格式错误']);
        }

        // [0][4] 表示状态码，[0][6] 表示凭证编号
        if (!isset($decodedResult[0]) || !array_key_exists(4, $decodedResult[0])) {
            return response()->json(['code' => 500, 'msg' => '金蝶接口返回数据缺失']);
        }

        $status = $decodedResult[0][4];
        $jeCode = $decodedResult[0][6] ?? '';

        if ((string)$status === '0000') {
            $updateResult = DB::table('v_xs_total')
                ->where('id', $info['id'])
                ->update([
                    'status' => 2,
                    'cost_code' => $jeCode,
                    'updated_time' => date('Y-m-d H:i:s')
                ]);
            if (!$updateResult) {
                // 数据库更新失败
                return ['data'=>0,'code' => 204];
            }
            return ['data'=>$jeCode,'code' => 0];
        }

        return ['data'=>0,'code' => 204];

    }

  public function setStoredOutData($info)
  {
      $inventoryModel = new Inventory();
          //无税金额
          if($info['income']){
              $info['income'] = $info['income']; //  收入
              $info['account_number_1'] = $info['account_number_1'];
              $info['abstract_excluded'] = $info['abstract_excluded'];
              $info['asstActNumber2'] = $info['jin_customer_code'];
              $info['asstActName2'] = $info['jin_customer_name'];
              $info['asstActType2'] = '客户';
          }
          //销项税
          if($info['sales_tax']){
              $info['amount'] = $info['sales_tax'];
              $info['account_number_2'] = '2221.01.02';
              $info['amount_abstract'] = '应交税额_应交增值税_销项税额';
          }
          //含税金额
          if($info['tax_inclusive_amount']){
              $info['tax_included_amount'] = $info['tax_inclusive_amount'];
              $info['account_number_3'] = '1122.02';
              $info['included_abstract'] = '应收账款_暂估';
              $info['asstActNumber2'] = $info['jin_customer_code'];
              $info['asstActName2'] = $info['jin_customer_name'];
              $info['asstActType2'] = '客户';
          }

      $certificateData = $inventoryModel->getStoredOutData($info);
      $url = 'http://8.152.0.162/eas/loginAndVoucher';
      $result = $this->KingdeePost($url, $certificateData);

      if ($result === false) {
          return response()->json(['code' => 500, 'msg' => '调用金蝶接口失败']);
      }

      $decodedResult = json_decode($result, true);
      if (json_last_error() !== JSON_ERROR_NONE || !is_array($decodedResult)) {
          // JSON 解析失败或不是数组
          return response()->json(['code' => 500, 'msg' => '金蝶接口返回格式错误']);
      }

      // [0][4] 表示状态码，[0][6] 表示凭证编号
      if (!isset($decodedResult[0]) || !array_key_exists(4, $decodedResult[0])) {
          return response()->json(['code' => 500, 'msg' => '金蝶接口返回数据缺失']);
      }

      $status = $decodedResult[0][4];
      $jeCode = $decodedResult[0][6] ?? '';

      if ((string)$status === '0000') {
          $updateResult = DB::table('v_xs_total')
              ->where('id', $info['id'])
              ->update([
                  'status' => 2,
                  'inc_code' => $jeCode,
                  'updated_time' => date('Y-m-d H:i:s')
              ]);
          if (!$updateResult) {
              // 数据库更新失败
              return ['data'=>0,'code' => 204];
          }
          return ['data'=>$jeCode,'code' => 0];
      }
      return ['data'=>0,'code' => 204];
  }



    public function generateSelect(Request $request)
    {
        return view('admin.surgical.xs_select_index');
    }

    public function generateSubmit(Request $request)
    {
        $type = $request->get('jin_supplier_code');
        $dataTime = $request->get('date');

        $supplierModel = new Supplier();
        $where =   [
            'customer_calculation' => $type,
            'data_time' => $dataTime,
        ];

        $data = $supplierModel->getData('v_xs_total',$where,'*');


        if (!$data){
            return response()->json(['code'=>204,'msg'=>'暂无数据']);
        }
        $income = 0;
        $sales_tax = 0;
        $tax_inclusive_amount = 0;
        foreach ($data as $value){
            $income+=$value['income'];//收入
            $sales_tax += $value['sales_tax'];//税额
            $tax_inclusive_amount += $value['tax_inclusive_amount'];//含税金额
        }

            $info['account_number_1'] = '6001.01.01';
            $info['abstract_excluded'] = '主营业务收入_内部销售_药装产品销售';
        //无税金额
            $info['income'] = $income; //  收入
            $info['account_number_1'] = '6001.01.01';
        //销项税
            $info['amount'] = $sales_tax;
            $info['account_number_2'] = '2221.01.02';
            $info['amount_abstract'] = '应交税额_应交增值税_销项税额';
        //含税金额
            $info['tax_included_amount'] = $tax_inclusive_amount;
            $info['account_number_3'] = '1122.02';
            $info['included_abstract'] = '应收账款_暂估';
            $info['asstActType2'] = '客户';



        $inventoryModel = new Inventory();
        $certificateData = $inventoryModel->setStoredOutData($info,$data,$dataTime);

        $url = 'http://8.152.0.162/eas/loginAndVoucher';
        $result = $this->KingdeePost($url, $certificateData);

        if ($result === false) {
            return response()->json(['code' => 500, 'msg' => '调用金蝶接口失败']);
        }

        $decodedResult = json_decode($result, true);

        $status = $decodedResult[0][4];
        $jeCode = $decodedResult[0][6] ?? '';

        if ((string)$status === '0000') {
            return response()->json(['code' => 0, 'errmsg' => '提交成功']);
        }else{
            return response()->json(['code' => 400, 'errmsg' => $status]);
        }
    }


}
